﻿using System;
using System.Data.Metadata.Edm;
using System.Data.Objects;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using Pasta.Medio.Concrete;
using Pasta.Medio.Configuration;

namespace Pasta.Medio
{
    static class Util
    {
		private static AppSettings Settings = Program.Settings;

        public static string ComputeSHA1(string filename)
        {
            byte[] hash;
            using (Stream stream = File.OpenRead(filename))
            {
                hash = SHA1.Create().ComputeHash(stream);
            }
            return Convert.ToBase64String(hash);
        }

		public static string ComputeSHA1(FileInfo fi)
		{
			byte[] hash;
			using (Stream stream = fi.OpenRead())
			{
				hash = SHA1.Create().ComputeHash(stream);
			}
			return Convert.ToBase64String(hash);
		}

		private static string FormatDate(DateTime? dt)
		{
			return dt.HasValue ? dt.Value.ToString(Settings.RenamePattern) : "-";
		}

		private static bool GetFolder(string path)
		{
			bool success = false;
			try
			{
				if (!Directory.Exists(path))
				{
					Directory.CreateDirectory(path);
					success = true;
				}
			}
			catch (Exception ex)
			{
				Results.CriticalError("Error accessing folder {0}:\n{1}\n", path, ex.Message);
			}
			return success;
		}


	}

	static class Extensions
	{
		public static string Right(this string value, int length)
		{
			int len = Math.Min(value.Length, Math.Abs(length));
			if (length <= 0)
				return value.Substring(0, value.Length - len);
			else
				return value.Substring(value.Length - len);
		}

		public static object RunMethod(this object instance, string name)
		{
			return instance.RunMethod(name, new object[0]);
		}

		public static object RunMethod(this object instance, string name, object[] args)
		{
			try
			{
				Type t = instance.GetType();
				MethodInfo mi = t.GetMethod(name);
				return mi.Invoke(instance, args);
			}
			catch (Exception ex)
			{
				string msg = ex.Message;
				return null;
			}
		}

	}

	public static class ObjectSetExtensions
	{
		public static int ClearDBTable<T>(this ObjectSet<T> objectSet) where T : class
		{
			// create metadataWorkspace
			objectSet.ToTraceString();
			//get storeItemCollection
			StoreItemCollection storeItemCollection = (StoreItemCollection)objectSet.Context.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);
			// get entity set
			EntitySet entSet = storeItemCollection.GetItems<EntityContainer>()[0].GetEntitySetByName(objectSet.EntitySet.Name, true);
			// get schema name
			string schemaName = entSet.MetadataProperties["Schema"].Value.ToString();
			//entity set is also a table name
			return objectSet.Context.ExecuteStoreCommand(string.Format("delete from {0}.{1}", schemaName, objectSet.EntitySet.Name));
		}
	}
}
